using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.Scheduled;
using IM.Easy.ScheduledServices.Dtos;
using IM.Easy.ScheduledServices.IServices;
using Mapster;

namespace IM.Easy.ScheduledServices.Services
{
    public class ScheduledJobService : AppServices<ScheduledJob>, IScheduledJobService
    {

        public ScheduledJobService(ISqlSugarClient db) : base(db)
        {

        }

        public ScheduledJob Create(ScheduledJobCreateDto entity)
        {
            var instance = entity.Adapt<ScheduledJob>();
            //处理任务启动状态
            if (instance.Trigger.StartMode == TriggerStartMode.Manual) instance.Status = SchedulerStatus.Pending;  //待启动
            else instance.Status = SchedulerStatus.Normal;      //已启动

            instance = Context.InsertNav(instance)
                .Include(s => s.Extend)
                .Include(s => s.Trigger)
                .ExecuteReturnEntity();
            return instance;
        }

        public ScheduledJob GetScheduled(dynamic id)
        {
            var instance = Context.Queryable<ScheduledJob>()
                .IncludesAllFirstLayer()
                .InSingle(id);
            return instance;
        }

        public PageResponse<ScheduledJobDto> GetPageList(ScheduledJobQueryDto query)
        {
            var queryable = Context.Queryable<ScheduledJob>();
            var exp = Expressionable.Create<ScheduledJob>();
            exp = exp.AndIF(!string.IsNullOrEmpty(query.Name), s => s.Name.Contains(query.Name));
            var page = queryable
                 .IncludesAllFirstLayer()
                 .Where(exp.ToExpression())
                 .ToPageList<ScheduledJob, ScheduledJobDto>(query);
            return page;
        }

        public override bool Update(ScheduledJob entity)
        {
            // TODO: 添加更新逻辑
            return Context.Updateable(entity).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool Delete(params Guid[] Id)
        {
            var flag = Context.DeleteNav<ScheduledJob>(s => Id.Contains(s.Id))
                    .Include(s => s.Extend)
                    .Include(s => s.Trigger)
                    .ExecuteCommand();
            return flag;
        }

        /// <summary>
        /// 获取所有调度任务
        /// </summary>
        /// <returns></returns>
        public List<ScheduledJob> GetScheduleds()
        {
            var scheduleds = Context.Queryable<ScheduledJob>()
                 .IncludesAllFirstLayer()
                 .ToList();
            return scheduleds;
        }


    }
}
